﻿/*************************************************************************************
 * 文 件 名:   HK_AutoSwitchToUTF8
 * 
 * 描    述:   自动将新建和导入的脚本，转为UTF-8编码，防止脚本在Inspector面板预览中文时产生乱码
 * 
 * 版    本：  V1.1
 * 创 建 者：  京产肠饭、Kane
 * 创建时间：  2022/1/15
 * 链   接：  https://gitee.com/JingChanChangFan/hk_-unity-tools
*************************************************************************************/

using UnityEditor;
using System.IO;
using System.Text;
using UnityEngine;

[InitializeOnLoad]
public class HK_AutoSwitchToUTF8 : AssetPostprocessor
{
    static HK_AutoSwitchToUTF8()
    {
        HK_ToolSetting.ChangeAutoSwitchToUTF8Event += OnChangeAutoSwitchToUTF8Event;
    }

    static void OnChangeAutoSwitchToUTF8Event(bool _isEnable)
    {
        isEnable = _isEnable;
    }

    static bool isEnable = true;

    // 将新建脚本转换为UTF-8
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        if (!isEnable) return;

        if (importedAssets.Length == 0) return;  // 如果没有导入新资源的话，直接return

        string dicPath = Directory.GetCurrentDirectory();

        foreach (string importedAsset in importedAssets)
        {
            if (!importedAsset.Contains("Assets/")) // 如果不是Assets中的脚本资源，则忽略
                return;

            string filePath = dicPath + "/" + importedAsset;

            // 根据名字+创建时间 来判断是否处理过这个文件
            string exitKey = importedAsset + new FileInfo(filePath).CreationTime;
            if (EditorPrefs.GetString(exitKey) == "IsProcessed")
                return;

            string extension = Path.GetExtension(filePath);

            if (extension == ".cs" || extension == ".CS")
            {
                Encoding encoding = GetFileEncodeType(filePath);

                string key = importedAsset + new FileInfo(filePath).CreationTime.ToString();

                if (encoding == Encoding.UTF8)
                {
                    Debug.Log(importedAsset + " 不进行处理");
                    EditorPrefs.SetString(key, "IsProcessed");
                    return;
                }

                var fileAllTxt = File.ReadAllText(filePath, Encoding.GetEncoding("GB18030"));

                File.WriteAllText(filePath, fileAllTxt, Encoding.UTF8);

                Debug.LogFormat("将{0}转为UTF-8编码格式", key);

                EditorPrefs.SetString(key, "IsProcessed");
            }
        }
    }

    public static Encoding GetFileEncodeType(string filename)
    {
        using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
        {
            BinaryReader br = new BinaryReader(fs);
            byte[] buffer = br.ReadBytes(2);

            if (buffer[0] >= 0xEF)
            {
                if (buffer[0] == 0xEF && buffer[1] == 0xBB)
                {
                    return Encoding.UTF8;
                }
                else if (buffer[0] == 0xFE && buffer[1] == 0xFF)
                {
                    return Encoding.BigEndianUnicode;
                }
                else if (buffer[0] == 0xFF && buffer[1] == 0xFE)
                {
                    return Encoding.Unicode;
                }
                else
                {
                    return Encoding.Default;
                }
            }
            else
            {
                return Encoding.Default;
            }
        }
    }
}

